<?php


class ConfigManager {
  const PROJECTS_DIR = "../projects" ;
  const SERVER_PROJECTS_LIST = "../server/conf/projects-list.xml" ;

  public static function readProjectName() {
      // zaczytanie nazwy projektu z katalogu
      $projects = array() ;
      $main=opendir( ConfigManager:: PROJECTS_DIR );
      $i=1;
      while ($k=readdir($main)) {
        if( $k !== "." and $k !== ".." ) 
          $projects[] = $k ;
      }
      closedir($main); 
      if( count($projects) > 1 ) {
        print_r("W katalogu projects jest więcej niż jeden projekt - sytuacja nieobsługiwana") ;
        exit;
      }
      
      $dir_name = $projects[0] ;
      $xml = simplexml_load_file( ConfigManager:: PROJECTS_DIR."/$dir_name/.project" ) ;
      $xml_name = (string)$xml->name ; //->xpath("");
      
      if( $xml_name != $dir_name ) {
        print_r("Niezgodna nazwa katalogu z nazwą projektu") ;
        exit;
      }
      
      return $dir_name ;
  }
  
  public static function readDBSettings( $project_name ) {
      $xml = simplexml_load_file( ConfigManager::PROJECTS_DIR."/$project_name/conf/orm-conf.xml" ) ;
      $pr = $xml->xpath("//group[@active='true']/db");
 //     echo "<pre>" ;
     // print_r($pr[0]);
     // exit;
      return $pr[0];
    
  
  }
  
  public static function changeProjectName( $old_name, $new_name ) {
    if( $old_name != $new_name ) {
      // zmiana katalogu projektu
      rename( ConfigManager:: PROJECTS_DIR."/$old_name", ConfigManager::PROJECTS_DIR."/$new_name"  ) ;
      // zmiana wpisu w pliku konfiguracyjnym projektu - dla eklipsa
      $xml = simplexml_load_file( ConfigManager::PROJECTS_DIR."/$new_name/.project");
      $xml->name = $new_name ;
      file_put_contents( ConfigManager::PROJECTS_DIR."/$new_name/.project",$xml->asXML());
      // zmiana ustawień nazwy projektu w serwerze
      $xml = simplexml_load_file( ConfigManager::SERVER_PROJECTS_LIST );    
      $xml->project["id"] = $new_name;
      $xml->project["name"] = $new_name;
      $xml->project["path"] = "/".$new_name;
      file_put_contents( ConfigManager::SERVER_PROJECTS_LIST, $xml->asXML() );
    }
  }
  
  public static function changeDBSettings( $new_settings ) {
    $xml = simplexml_load_file( ConfigManager::PROJECTS_DIR."/{$new_settings["name"]}/conf/orm-conf.xml" );    
    
    foreach( $xml->databases->group as $db ) {
      if( $db["active"] == "true" ) {
        $db->db->host = $new_settings["host"] ; 
        $db->db->user = $new_settings["user"] ; 
        $db->db->name = $new_settings["dbname"] ; 
        if( strlen( $new_settings["password"] ) > 0 ) {
          $db->db->password = $new_settings["password"] ; 
        } else {
          $new_settings["password"] = (string) $db->db->password ;
        }
      }
    }
    
    file_put_contents( ConfigManager::PROJECTS_DIR."/{$new_settings["name"]}/conf/orm-conf.xml", $xml->asXML() );
  
    if( $new_settings["create"] == "tak" ) {
        ConfigManager::createTables( $new_settings ) ;
    }
  
  }
  
  // tworzy tabele na podstawie wpisów w pliku xml
  public static function createTables( $settings ) {
  
    $link = mysql_connect( $settings["host"], $settings["user"], $settings["password"] ) ;
    if( !$link ) die("nie można połączyć z bazą danych") ;
    
    $query_db_exist = "CREATE DATABASE IF NOT EXISTS `{$settings["dbname"]}` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci " ;
    mysql_query( $query_db_exist );
    
    // sprawdzenie czy baza danych jest pusta
    mysql_select_db( $settings["dbname"], $link);
    $tables = mysql_fetch_row( mysql_query( "SHOW TABLES" ) ) ;
    if( isset($tables[0]) ) die( 'baza danych posiada już tabele - przerwanie skryptu' ) ;
    
    $xml = simplexml_load_file( ConfigManager::PROJECTS_DIR."/{$settings["name"]}/conf/db-schema-cms.xml" );    
    //$i = 0 ;
    
    foreach( $xml->table as $table ) {
      $rows = array();
      $end_rows = array();
      foreach( $table->column as $column ) {
        $endrow = "";
        $row = "\t\t" ;
        if( isset($column["name"]) ) $row.= "`{$column["name"]}` ";
        if( isset($column["type"]) ) {
          $size = 0 ;
          if( isset($column["size"]) ) $size = (int)$column["size"] ;
          switch( (string)$column["type"] ) {
            case "INTEGER": {
              if( $size == 0 ) $size = 11 ;
              $row .= "int($size) " ;
            } break;
            case "TINYINT": {
              $row .= "smallint(6) " ;
            } break;
            case "SMALLINT": {
              $row .= "smallint(6) " ;
            } break;
            case "BIGINT": {
              if( $size == 0 ) $size = 20 ;
              $row .= "bigint($size) " ;
            } break;
            case "BIT": {
              $row .= "tinyint(1) " ;
            } break;
            case "BINARY": {
              if( $size == 0 ) $size = 254 ;
              $row .= "binary($size) " ;
            } break;
            case "CHAR": {
              if( $size == 0 ) $size = 255 ;
              $row .= "char($size) " ;
            } break;
            case "VARCHAR": {
              if( $size == 0 ) $size = 64 ;
              $row .= "varchar($size) " ;
            } break;
            case "LONGVARCHAR": {
              $row .= "mediumtext " ;
            } break;
            case "FLOAT": {
              $row .= "double " ;
            } break;
            case "DOUBLE": {
              $row .= "double " ;
            } break;
            case "DECIMAL": {
              $row .= "decimal(10,0) " ;
            } break;
            case "DATE": {
              $row .= "date " ;
            } break;
            case "TIME": {
              $row .= "time " ;
            } break;
            case "TIMESTAMP": {
              $row .= "datetime " ;
            } break;
          }
        }
        if( isset($column["required"]) ) {
          if( $column["required"] == "true" or ( isset($column["autoIncrement"]) and $column["autoIncrement"] == "true" ) or ( isset($column["primaryKey"]) and $column["primaryKey"] == "true" ) ) 
            $row .= "NOT NULL " ;
          else {
            if( $column["type"] != "LONGVARCHAR" ) {
              if( isset($column["default"] ) ) 
                $row .= "default '{$column["default"]}' " ;
              else  
                $row .= "default NULL " ;
              
            }
          }
        }
        
        if( isset($column["autoIncrement"]) and $column["autoIncrement"] == "true" ) $row.= "auto_increment ";
        
        if( isset($column["primaryKey"]) and $column["primaryKey"] == "true" ) $end_rows[] = "\t\tPRIMARY KEY  (`{$column["name"]}`)" ;
        
        $rows[] = $row ;
      }
      
      $rows = array_merge($rows, $end_rows);
      
      
      $sql_t = "CREATE TABLE IF NOT EXISTS `{$table["name"]}` (\n ".implode( ",\n", $rows ). "\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;\n" ;
      
      
      /*if( $i == 12 )  {
      
        echo "<pre>  $sql_t  \n\n\n\n\n\n\n";
        print_r($table);
        exit;
      
      } 
      ++$i ; */
      //$sql .= "$sql_t\n\n" ;
      //echo "  $sql_t  \n\n";
      
      
      mysql_query( $sql_t ) ;
      
      
      //print(mysql_error($result));
   
    }
    
    
   // echo "<pre> odtwarzamy bd" ;
    //print_r($sql);
    //exit; 
    mysql_close( $link ) ;
  
  }
  
  // zwraca komunikaty o błedach
  public static function checkData( $data ) {
     $msg = "<ul>" ;
     if( $data["password"] != $data["repassword"] ) 
        $msg .= "<li>Nie zgadza się hasło z jego powtórzeniem</li>" ;

     if( !is_writeable( ConfigManager::PROJECTS_DIR."/{$data["name_old"]}/.project"  )  ) 
        $msg .= "<li>Nie masz uprawnień aby zapisywać plik: ".ConfigManager:: PROJECTS_DIR."/$dir_name/.project"."</li>" ;
     
     if( !is_writeable( ConfigManager::PROJECTS_DIR."/{$data["name_old"]}/conf/orm-conf.xml"  )  ) 
        $msg .= "<li>Nie masz uprawnień aby zapisywać plik: ".ConfigManager:: PROJECTS_DIR."/$project_name/conf/orm-conf.xml"."</li>" ;
        
     if( !is_writeable( ConfigManager::SERVER_PROJECTS_LIST )  ) 
        $msg .= "<li>Nie masz uprawnień aby zapisywać plik: ".ConfigManager::SERVER_PROJECTS_LIST."</li>" ;

     $msg .= "</ul>" ;
     if( strlen( $msg ) > 10 ) return $msg ;
     
     return "" ;
  }

}



?>